export default {
  data() {
    //序号
    const rows = (t, r, i) => {
      const { current, pageSize } = this.pagination
      return (pageSize ?? 10) * ((current ?? 1) - 1) + 1 + i
    }
    return {
      loading: true, // 加载中
      loadParams: {}, // 请求参数
      dataSource: [], // 数据源
      loadApi: undefined, //请求table的接口  必须被混合使用的组件覆盖
      pagination: {
        total: 0,
        showLessItems: true,
        // hideOnSinglePage: true, //只有一页时是否隐藏分页器
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: t => `共${t}条`
      }, // 分页
      columns: [
        { title: '序号', key: 'rows', width: 50, align: 'center', customRender: rows } //序号
      ]
    }
  },
  methods: {
    // 加载数据
    loadData() {
      if (!this.loadApi) return
      this.loading = true
      this.loadApi(this.loadParams)
        .then(res => {
          this.dataSource = res.list
          this.pagination.total = res.total
        })
        .catch(err => {
          this.dataSource = []
          this.pagination.total = 0
          this.$message.error(err)
        })
        .finally(() => {
          this.loading = false
        })
    },
    //分页、排序、筛选变化时触发
    tableChange(pagination, filters, sorter) {
      this.pagination = pagination
      const params = {
        current: pagination.current > 1 ? pagination.current : undefined,
        pageSize: pagination.pageSize > 10 ? pagination.pageSize : undefined
      }
      if (filters && Object.keys(filters).length > 0) {
        Object.assign(params, { ...filters })
      }
      if (sorter?.field) {
        Object.assign(params, { sortKey: sorter.field, sortValue: sorter.order })
      }
      Object.assign(this.loadParams, params)
      this.loadData()
    }
  }
}
